# -*- coding: utf-8 -*-
#
#  Copyright (C) 2009-20010 Universidad Rey Juan Carlos, GSyC/LibreSoft
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Gato Luis <jgato@libresoft.es>

from django.http import HttpResponse

from format.utils import  getResponseFormat, generateResponse
from social.layers.my_layers_manager import layers_info, layers_request, layers_icon
from utils import error, get_limits, get_num_pages

def _select_limits(from_limit, to_limit, nodes):
    
    return nodes[from_limit:to_limit]
     
def _type_response(type):

    if type == "note":
        return "notes", "note_list"
    elif type == "video":
        return "videos", "video_list"
    elif type == "photo":
        return "photos", "photo_list"
    elif type == "sound":
        return "sounds", "sound_list"
    elif type == "person":
        return "users", "user_list" 
    
def layer_request(request, layer_id):
    
    format = getResponseFormat (request)
     
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")

    if "search" in request.GET:
        search = request.GET["search"]
    else:
        return error(format, "\"search\" parameter is mandatory")

    options = request.GET.copy()
    options["user"] = request.user
    
    success, response = layers_request(layer_id, search, options)
    
    # very ugly path, the client should control errors with success = False
    if success == False and layer_id == "panoramio":
        success = True
        response = []
    if success:
        
        f, t, page, elems = get_limits(request)

        total_pages = get_num_pages(len(response), elems)
            
        data_page = _select_limits (f, t, response)

        # we assume all the elements of the same type
        # how to render empty list?? #FIXME
        if len(response) == 0:
            id_type = "photos"
            render_type = "photo_list"
        else:
            try: #FIXME PLEASE!!! with rendering with a generic search template
                id_type, render_type = _type_response (response[0].type)
            except:
                if options["category"]:
                    id_type, render_type = _type_response (options["category"])
                else:
                    id_type = "photos"
                    render_type = "photo_list"
         
        data = {'code'    : '200',
                id_type   : data_page,
                'page'    : page,
                'elems'   : len(data_page),
                'total_pages' : total_pages,
                'type'    : render_type }

        #Fixme: this code will be generic with unified templates
        
        if id_type == "photos":
            return generateResponse(format, data, "photo/list")
        elif id_type == "videos":
            return generateResponse(format, data, "video/list")
        elif id_type == "notes":
            return generateResponse(format, data, "note/list")
        elif id_type == "sounds":
            return generateResponse(format, data, "sound/list")
        elif id_type == "users":
            return generateResponse(format, data, "user/list")
        
#        data = {"code"   : "200",
#                "results" : response }                
#
#        return generateResponse(format, data, "search/list")
    else:
        return error(format, response)


def layer_info(request, layer_id):

    format = getResponseFormat (request)
    
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")
    
    success, response = layers_info(layer_id)
    
    if success:
        data = {'code'         : 200,
                'description'  : response,}
        return generateResponse(format, data, "ok" )
    else:
        return error(response)

    
def layer_icon(request, layer_id):
    
    format = getResponseFormat (request)
    
    if not request.user.is_authenticated():
        return error(format, "The user is not authenticated")

    success, data = layers_icon(layer_id)
    
    if success:
        return HttpResponse(data, mimetype="image/png")
    else:
        return error(format, data)
    
    
    
    
